import { NextRequest, NextResponse } from 'next/server'
import  prisma  from '@/lib/prisma'
import { getUser } from '@/lib/authUtils'

// 获取用户的课程列表
export async function GET(request: NextRequest): Promise<NextResponse> {
  try {
    const userResult = await getUser(request)
    if (!userResult || userResult instanceof NextResponse) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }
    const userId = userResult as string

    const courses = await prisma.vms_course.findMany({
      where: {
        user_id: userId
      },
      include: {
        sections: {
          orderBy: {
            order: 'asc'
          }
        },
        _count: {
          select: {
            participants: true,
            access_logs: true
          }
        }
      },
      orderBy: {
        created_at: 'desc'
      }
    })

    return NextResponse.json(courses)
  } catch (error) {
    console.error('Error fetching courses:', error)
    return NextResponse.json(
      { error: 'Internal server error', details: error instanceof Error ? error.message : 'Unknown error' },
      { status: 500 }
    )
  }
}

// 创建新课程
export async function POST(request: NextRequest): Promise<NextResponse> {
  try {
    const userResult = await getUser(request)
    if (!userResult || userResult instanceof NextResponse) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }
    const userId = userResult as string

    // Verify user exists in database
    const userExists = await prisma.vms_user.findUnique({
      where: { id: userId }
    })
    
    if (!userExists) {
      return NextResponse.json({ error: 'User not found' }, { status: 404 })
    }

    const body = await request.json()
    const { 
      title, 
      description, 
      content_description, 
      cover_image, 
      is_free, 
      max_participants, 
      start_time, 
      end_time, 
      access_password,
      status 
    } = body

    const course = await prisma.vms_course.create({
      data: {
        title,
        description,
        content_description,
        cover_image,
        is_free: is_free ?? true,        // 修改：从 is_public 改为 is_free
        max_participants,
        start_time: start_time ? new Date(start_time) : null,
        end_time: end_time ? new Date(end_time) : null,
        access_password,
        status: status ?? 'draft',       // 新增：课程状态
        user_id: userId
      },
      include: {
        sections: {
          orderBy: {
            order: 'asc'
          }
        }
      }
    })

    return NextResponse.json(course)
  } catch (error) {
    console.error('Error creating course:', error)
    return NextResponse.json(
      { error: 'Internal server error', details: error instanceof Error ? error.message : 'Unknown error' },
      { status: 500 }
    )
  }
}